import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, removeToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  const hasToken = getToken()
  if (hasToken) {
    if (store.getters.userInfo) {
      next()
    } else {
      try {
        await store.dispatch('user/getuserInfoActions')
        // console.log(store.getters.userInfo)

        // 去登陆页
        if (to.path === '/login') {
          next('/')
        } else {
          // 不是去登陆页
          next()
        }
      } catch (error) {
        removeToken()
        Message.warning('用户信息有误，请重新登陆')
        next(`/login?redirect=${to.path}`)
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Message('请先登陆')
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
